package cn.lblbc.countdown

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.NumberPicker
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.util.Locale

class MainActivity : AppCompatActivity() {
    
    // UI组件
    private lateinit var hourPicker: NumberPicker
    private lateinit var minutePicker: NumberPicker
    private lateinit var secondPicker: NumberPicker
    private lateinit var timePickerLayout: LinearLayout
    private lateinit var countdownLayout: View
    private lateinit var countdownText: TextView
    private lateinit var circularProgress: CircularProgressView
    private lateinit var controlBtn: Button
    private lateinit var resetBtn: Button
    
    // 倒计时相关
    private var countDownTimer: CountDownTimer? = null
    private var totalTimeInMillis: Long = 0
    private var remainingTimeInMillis: Long = 0
    private var isRunning = false
    private var currentTheme = THEME_CYBERPUNK
    
    companion object {
        const val PREFS_NAME = "CountdownPrefs"
        const val THEME_KEY = "SelectedTheme"
        const val THEME_CYBERPUNK = "cyberpunk"
        const val THEME_CLASSIC = "classic"
        const val THEME_OCEAN = "ocean"
        const val THEME_SUNSET = "sunset"
        const val THEME_FOREST = "forest"
        const val THEME_MINIMALIST = "minimalist"
        const val THEME_DEEPSPACE = "deepspace"
        const val THEME_CRT = "crt"
        const val THEME_CANDY = "candy"
        const val THEME_FIRE = "fire"
        
        val THEME_NAMES = arrayOf(
            "赛博朋克", "经典暗色", "海洋", "日落", "森林",
            "极简白色", "深空黑", "复古CRT", "粉彩糖果", "火焰"
        )
        
        val THEME_KEYS = arrayOf(
            THEME_CYBERPUNK, THEME_CLASSIC, THEME_OCEAN, THEME_SUNSET, THEME_FOREST,
            THEME_MINIMALIST, THEME_DEEPSPACE, THEME_CRT, THEME_CANDY, THEME_FIRE
        )
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        // 应用保存的主题
        applySavedTheme()
        
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        
        initViews()
        setupNumberPickers()
        setupButtons()
    }
    
    override fun onResume() {
        super.onResume()
        
        // 获取保存的主题
        val prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
        val savedTheme = prefs.getString(THEME_KEY, THEME_CYBERPUNK) ?: THEME_CYBERPUNK
        
        // 检查主题是否已更改
        if (savedTheme != currentTheme) {
            // 重新创建Activity以应用新主题
            recreate()
        }
    }
    
    private fun applySavedTheme() {
        val prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
        currentTheme = prefs.getString(THEME_KEY, THEME_CYBERPUNK) ?: THEME_CYBERPUNK
        
        when (currentTheme) {
            THEME_CYBERPUNK -> setTheme(R.style.Theme_Countdown_Cyberpunk)
            THEME_CLASSIC -> setTheme(R.style.Theme_Countdown_Classic)
            THEME_OCEAN -> setTheme(R.style.Theme_Countdown_Ocean)
            THEME_SUNSET -> setTheme(R.style.Theme_Countdown_Sunset)
            THEME_FOREST -> setTheme(R.style.Theme_Countdown_Forest)
            THEME_MINIMALIST -> setTheme(R.style.Theme_Countdown_Minimalist)
            THEME_DEEPSPACE -> setTheme(R.style.Theme_Countdown_DeepSpace)
            THEME_CRT -> setTheme(R.style.Theme_Countdown_CRT)
            THEME_CANDY -> setTheme(R.style.Theme_Countdown_Candy)
            THEME_FIRE -> setTheme(R.style.Theme_Countdown_Fire)
        }
    }
    
    private fun initViews() {
        hourPicker = findViewById(R.id.hourPicker)
        minutePicker = findViewById(R.id.minutePicker)
        secondPicker = findViewById(R.id.secondPicker)
        timePickerLayout = findViewById(R.id.timePickerLayout)
        countdownLayout = findViewById(R.id.countdownLayout)
        countdownText = findViewById(R.id.countdownText)
        circularProgress = findViewById(R.id.circularProgress)
        controlBtn = findViewById(R.id.controlBtn)
        resetBtn = findViewById(R.id.resetBtn)
        
        // 设置圆形进度条的最大值
        circularProgress.setMaxProgress(100f)
        
        // 找到并设置三点按钮的点击事件
        val settingsButton = findViewById<ImageView>(R.id.settings_button)
        settingsButton.setOnClickListener {
            val intent = Intent(this, SettingsActivity::class.java)
            startActivity(intent)
        }
    }
    
    private fun setupNumberPickers() {
        // 设置小时选择器
        hourPicker.minValue = 0
        hourPicker.maxValue = 23
        hourPicker.value = 0
        
        // 设置分钟选择器
        minutePicker.minValue = 0
        minutePicker.maxValue = 59
        minutePicker.value = 5
        
        // 设置秒钟选择器
        secondPicker.minValue = 0
        secondPicker.maxValue = 59
        secondPicker.value = 0
    }
    
    private fun setupButtons() {
        controlBtn.setOnClickListener {
            if (isRunning) {
                pauseCountdown()
            } else {
                startCountdown()
            }
        }
        
        resetBtn.setOnClickListener {
            resetCountdown()
        }
    }
    
    private fun startCountdown() {
        if (!isRunning) {
            // 如果还没有设置过时间或者已经完成了一次倒计时，则获取新的时间
            if (remainingTimeInMillis <= 0) {
                val hours = hourPicker.value
                val minutes = minutePicker.value
                val seconds = secondPicker.value
                
                totalTimeInMillis = ((hours * 3600) + (minutes * 60) + seconds) * 1000L
                remainingTimeInMillis = totalTimeInMillis
                
                if (totalTimeInMillis <= 0) {
                    // 如果没有设置时间，提示用户
                    androidx.appcompat.app.AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("请先设置倒计时时间")
                        .setPositiveButton("确定", null)
                        .show()
                    return
                }
            }
            
            // 切换到倒计时视图
            switchToCountdownView()
            
            // 启动倒计时
            startTimer()
            isRunning = true
            controlBtn.text = "暂停"
        }
    }
    
    private fun pauseCountdown() {
        if (isRunning) {
            countDownTimer?.cancel()
            isRunning = false
            controlBtn.text = "继续"
        }
    }
    
    private fun resetCountdown() {
        countDownTimer?.cancel()
        isRunning = false
        remainingTimeInMillis = 0
        controlBtn.text = "开始"
        
        // 切换到时间设置视图
        switchToTimePickerView()
    }
    
    private fun startTimer() {
        countDownTimer?.cancel()
        countDownTimer = object : CountDownTimer(remainingTimeInMillis, 100) {
            override fun onTick(millisUntilFinished: Long) {
                remainingTimeInMillis = millisUntilFinished
                updateCountdownDisplay()
            }
            
            override fun onFinish() {
                remainingTimeInMillis = 0
                updateCountdownDisplay()
                onCountdownFinished()
            }
        }.start()
    }
    
    private fun updateCountdownDisplay() {
        // 更新文本显示
        val hours = (remainingTimeInMillis / 1000) / 3600
        val minutes = ((remainingTimeInMillis / 1000) % 3600) / 60
        val seconds = (remainingTimeInMillis / 1000) % 60
        
        countdownText.text = String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds)
        
        // 更新圆形进度条
        if (totalTimeInMillis > 0) {
            val progress = 100f - (remainingTimeInMillis.toFloat() / totalTimeInMillis.toFloat() * 100f)
            circularProgress.setProgress(progress)
        }
    }
    
    private fun switchToCountdownView() {
        // 隐藏时间选择器，显示倒计时器
        timePickerLayout.visibility = View.GONE
        countdownLayout.visibility = View.VISIBLE
        
        // 更新倒计时显示
        updateCountdownDisplay()
    }
    
    private fun switchToTimePickerView() {
        // 隐藏倒计时器，显示时间选择器
        countdownLayout.visibility = View.GONE
        timePickerLayout.visibility = View.VISIBLE
    }
    
    private fun onCountdownFinished() {
        isRunning = false
        controlBtn.text = "开始"
        
        // 执行结束动画
        playFinishAnimation()
        
        // 显示结束对话框
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("时间到！")
            .setMessage("倒计时已完成")
            .setPositiveButton("确定") { _, _ ->
                resetCountdown()
            }
            .setCancelable(false)
            .show()
    }
    
    private fun playFinishAnimation() {
        // 缩放动画
        val scaleX = android.animation.ObjectAnimator.ofFloat(countdownText, "scaleX", 1f, 1.2f, 1f)
        scaleX.duration = 500
        
        val scaleY = android.animation.ObjectAnimator.ofFloat(countdownText, "scaleY", 1f, 1.2f, 1f)
        scaleY.duration = 500
        
        val animatorSet = android.animation.AnimatorSet()
        animatorSet.playTogether(scaleX, scaleY)
        animatorSet.start()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        countDownTimer?.cancel()
    }
}